import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:io';
import 'profile_logic.dart';

/// 我的页面视图 - Profile Page View
/// 
/// 显示用户信息、设置选项和应用功能
/// Displays user information, settings options, and app features
class ProfileView extends GetView<ProfileLogic> {
  const ProfileView({super.key});

  @override
  Widget build(BuildContext context) {
    // GetBuilder作为最外层包裹Widget - GetBuilder as the outermost wrapper widget
    // 每个View中只能有一个GetBuilder - Only one GetBuilder per View
    return GetBuilder<ProfileLogic>(
      init: ProfileLogic(),
      builder: (controller) {
        final state = controller.state;
        
        return Scaffold(
          appBar: AppBar(
            title: const Text(
              '我的',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
            backgroundColor: Colors.white,
            foregroundColor: Colors.black87,
            elevation: 0,
            automaticallyImplyLeading: false, // 隐藏返回按钮
          ),
          body: state.isLoading
              ? const Center(child: CircularProgressIndicator())
              : ListView(
                  padding: const EdgeInsets.all(16),
                  children: [
                    // 用户信息卡片 - User Info Card
                    _buildUserInfoCard(state),
                    
                    const SizedBox(height: 24),
                    
                    // 编辑器设置 - Editor Settings
                    _buildSectionHeader('编辑器设置'),
                    _buildSettingTile(
                      icon: Icons.text_format,
                      title: '默认格式',
                      subtitle: _getFormatDisplayName(state.defaultFormat),
                      onTap: () => controller.showFormatDialog(),
                    ),
                    _buildSettingTile(
                      icon: Icons.auto_awesome,
                      title: '自动保存',
                      subtitle: state.autoSave ? '已开启' : '已关闭',
                      trailing: Switch(
                        value: state.autoSave,
                        onChanged: controller.toggleAutoSave,
                      ),
                    ),
                    
                    const SizedBox(height: 24),
                    
                    // 存储设置 - Storage Settings
                    _buildSectionHeader('存储设置'),
                    _buildSettingTile(
                      icon: Icons.storage,
                      title: '存储位置',
                      subtitle: _getShortPath(state.storagePath),
                      onTap: () => controller.showStorageDialog(),
                    ),
                    _buildSettingTile(
                      icon: Icons.folder_open,
                      title: '自定义存储路径',
                      subtitle: state.customStoragePath.isEmpty ? '使用默认路径' : _getShortPath(state.customStoragePath),
                      onTap: () => controller.showCustomStorageDialog(),
                    ),
                    _buildSettingTile(
                      icon: Icons.backup,
                      title: '自动备份',
                      subtitle: state.autoBackup ? '已开启' : '已关闭',
                      trailing: Switch(
                        value: state.autoBackup,
                        onChanged: controller.toggleAutoBackup,
                      ),
                    ),
                    
                    const SizedBox(height: 24),
                    
                    // 通用设置 - General Settings (注释掉深色模式和国际化)
                    // _buildSectionHeader('通用设置'),
                    // _buildSettingTile(
                    //   icon: Icons.language,
                    //   title: '语言',
                    //   subtitle: state.language == 'zh-CN' ? '中文' : 'English',
                    //   onTap: () => controller.showLanguageDialog(),
                    // ),
                    // _buildSettingTile(
                    //   icon: Icons.dark_mode,
                    //   title: '深色模式',
                    //   subtitle: state.isDarkMode ? '已开启' : '已关闭',
                    //   trailing: Switch(
                    //     value: state.isDarkMode,
                    //     onChanged: controller.toggleDarkMode,
                    //   ),
                    // ),
                    
                    // 账户设置 - Account Settings
                    _buildSectionHeader('账户'),
                    _buildSettingTile(
                      icon: Icons.login,
                      title: '登录',
                      subtitle: '登录以同步数据',
                      onTap: () => controller.navigateToLogin(),
                    ),
                    
                    const SizedBox(height: 24),
                    
                    // 关于 - About
                    _buildSectionHeader('关于'),
                    _buildSettingTile(
                      icon: Icons.info,
                      title: '版本信息',
                      subtitle: 'v${state.appVersion}',
                      onTap: () => controller.showAboutDialog(),
                    ),
                    _buildSettingTile(
                      icon: Icons.help,
                      title: '帮助与支持',
                      subtitle: '使用指南和常见问题',
                      onTap: () => controller.showHelpDialog(),
                    ),
                  ],
                ),
        );
      },
    );
  }

  /// 构建用户信息卡片 - Build User Info Card
  /// Displays user avatar, name, and basic information
  /// 显示用户头像、姓名和基本信息
  Widget _buildUserInfoCard(state) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            // 用户头像 - User Avatar
            CircleAvatar(
              radius: 30,
              backgroundColor: Colors.blue.shade100,
              child: state.avatarPath.isNotEmpty
                  ? ClipOval(
                      child: Image.asset(
                        state.avatarPath,
                        width: 60,
                        height: 60,
                        fit: BoxFit.cover,
                      ),
                    )
                  : Icon(
                      Icons.person,
                      size: 30,
                      color: Colors.blue.shade600,
                    ),
            ),
            const SizedBox(width: 16),
            
            // 用户信息 - User Info
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    state.nickname,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    state.isLoggedIn ? state.email : '未登录',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            
            // 编辑按钮 - Edit Button
            IconButton(
              onPressed: () {
                // 未来功能：编辑用户信息
                Get.snackbar(
                  '提示',
                  '此功能暂未开放',
                  snackPosition: SnackPosition.BOTTOM,
                );
              },
              icon: const Icon(Icons.edit),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建分组标题 - Build Section Header
  /// Creates a styled section header for grouping settings
  /// 为设置分组创建样式化的分组标题
  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w600,
          color: Colors.blue,
        ),
      ),
    );
  }

  /// 构建设置项 - Build Setting Tile
  /// Creates a setting item with icon, title, subtitle, and optional trailing widget
  /// 创建带有图标、标题、副标题和可选尾部组件的设置项
  Widget _buildSettingTile({
    required IconData icon,
    required String title,
    required String subtitle,
    Widget? trailing,
    VoidCallback? onTap,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Icon(icon, color: Colors.blue),
        title: Text(
          title,
          style: const TextStyle(fontWeight: FontWeight.w500),
        ),
        subtitle: Text(subtitle),
        trailing: trailing ?? const Icon(Icons.chevron_right),
        onTap: onTap,
      ),
    );
  }

  /// 获取格式显示名称 - Get Format Display Name
  /// Returns user-friendly format names
  /// 返回用户友好的格式名称
  String _getFormatDisplayName(String format) {
    switch (format) {
      case 'md':
        return 'Markdown';
      case 'txt':
        return '文本文件';
      case 'doc':
        return 'Word文档';
      default:
        return format.toUpperCase();
    }
  }

  /// 获取短路径 - Get Short Path
  /// Returns a shortened version of the storage path for display
  /// 返回用于显示的存储路径的缩短版本
  String _getShortPath(String path) {
    if (path.isEmpty) return '未设置';
    
    // 如果路径太长，只显示最后两个目录
    final parts = path.split(Platform.isWindows ? '\\' : '/');
    if (parts.length > 2) {
      return '.../${parts[parts.length - 2]}/${parts[parts.length - 1]}';
    }
    return path;
  }
}